package com.longai.service;

import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Properties;
import java.util.Random;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.swing.ImageIcon;

import org.springframework.core.io.support.PropertiesLoaderUtils;
import org.springframework.web.multipart.MultipartFile;

import com.longai.model.UploadFileInfo;
import com.longai.model.User;

import functions.GetProperties;

public class FileUpload {
	public  static UploadFileInfo upload(MultipartFile file,String type,HttpServletRequest request) throws IOException{
		int width = Integer.parseInt(GetProperties.getValue("config", "picWidth"));
		int height = Integer.parseInt(GetProperties.getValue("config", "picHeight"));
		UploadFileInfo uploadFileInfo =upload(file, type, request,width,height);
		return uploadFileInfo;
	}
	
	public static UploadFileInfo uploadUserIcon(MultipartFile file,HttpServletRequest request,User user) throws NumberFormatException, IOException{
		//UserService userService = new UserService();
		System.out.println(user.getProfilepic());
		if(user.getProfilepic()!=null){
			String name = user.getProfilepic(); 
			System.out.println(name);
			String realPath = request.getSession().getServletContext().getRealPath(File.separator);
			System.out.println("start delete");
			PictureService.deleteImage("userIcon", name,realPath);
			System.out.println("complete delete");
		}
		String width = GetProperties.getValue("config", "userIconWidth");
		String height = GetProperties.getValue("config", "userIconHeight");
		UploadFileInfo upload = upload(file, "userIcon", request, Integer.parseInt(width), Integer.parseInt(height));
		return upload;
	}
	
	
	public  static UploadFileInfo upload(MultipartFile file,String type,HttpServletRequest request,int width,int height) throws IOException{
		  Properties fileUploadUrl = PropertiesLoaderUtils.loadAllProperties("conf/config.properties");
		  String serverpath = request.getSession().
	                getServletContext().getRealPath(File.separator); 
		  String path=fileUploadUrl.getProperty(type);
		  UploadFileInfo upload = new UploadFileInfo();
	        if (!file.isEmpty()) {
	            try {
	                byte[] bytes = file.getBytes();
	                String name = file.getOriginalFilename();
	                int index=name.indexOf(".");
	                String format=name.substring(index);
	                name=RandomString(8)+System.currentTimeMillis()+format;
	                path=serverpath+path;
	                path=path+name;
	                BufferedOutputStream stream =
	                        new BufferedOutputStream(new FileOutputStream(new File(path)));
	                if(width!=0){
	                	System.out.println("nail start");
	                	String nailPath=fileUploadUrl.getProperty("nail");
	                	path = serverpath+nailPath+name;
	                	BufferedImage imageIO = ImageIO.read(new ByteArrayInputStream(bytes));
	                	PictureService.saveImageAsJpg(imageIO, format.substring(1),path, width, height);
	                }
	                stream.write(bytes);
	                stream.close();
	                upload.setName(name);
	                upload.setStatus(true);
	                upload.setTs(new Long(System.currentTimeMillis()));
	                return upload;
	            } catch (Exception e) {
	            	upload.setStatus(false);
	                return upload;
	            }
	        } else {
	        	upload.setStatus(false);
	            return upload;
	        }
	}
	
	
	
	public static String RandomString(int length) {  
	    String str = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";  
	    Random random = new Random();  
	    StringBuffer buf = new StringBuffer();  
	    for (int i = 0; i < length; i++) {  
	        int num = random.nextInt(62);  
	        buf.append(str.charAt(num));  
	    }  
	    return buf.toString();  
	}  
}
